package com.gehj.base;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PersistableBundle;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.gehj.alluitls.androidUtils.NotificationUtils;
import com.gehj.alluitls.androidUtils.PermissionConstant;
import com.gehj.alluitls.androidUtils.PermissionUtils;

import java.lang.reflect.Field;

/**
  *
  * @ClassName:      BaseActivity
  * @Description:    以下主要功能
 * 1，动态权限集体获取 fixme 权限初始化可以在登录页进行处理 工具类中有单个权限处理，可以在使用时候再次申请权限
 * 2， 页面写button
 * TODO handler 内存泄漏 泄漏处理
 * TODO HandlerThread IntentService NIO代码实验
 * TODO 内存泄漏的那几个点 handler的弱引用 布局 看面试题
 * TODO mvvm多写
 * TODO 封webview的坑
 * TODO 进程保活方案
 * 3，二次点击退出
  * @Author:         gehj
  * @CreateDate:     2020/12/15 14:37
 */

public class BaseActivity extends AppCompatActivity {

    private Boolean isOPenNotify;//是否开启通知



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        checkNotify();
        //观察app是在前台还是后台，BaseActivityObserver需要改造
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new BaseActivityObserver());

        PermissionUtils.getPermissions(this, PermissionConstant.ALL_PERMISSION);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        //TODO 横竖屏转动
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }


    /**
     * 检查是否开启通知
     */
    private void checkNotify() {
        isOPenNotify = NotificationUtils.checkNotifySetting(this);
        if (!isOPenNotify) {
            Intent intent = new Intent(this, MainActivity_check_notification.class);
            startActivity(intent);
        }
    }


    //设置字体大小不随手机设置而改变
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }


    /**
     * 二次退出
     */
    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 1500) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;// 更新firstTime
                } else {
                    finishAffinity();//关闭当前activity所属的activity栈中所有的activity
                }
                break;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //releaseHandlers();//用反射关闭所有handler,防止内存泄漏

    }


    /**
     * 有时候关闭后也要进行handler操作，不适合用此方法，一般的都适合
     */
    private void releaseHandlers() {
        Class<?> clazz = getClass();
        Field[] fields = clazz.getDeclaredFields();
        if (fields == null || fields.length <= 0) {
            return;
        }

        for (Field field : fields) {
            field.setAccessible(true);
            if (!Handler.class.isAssignableFrom(field.getType())) continue;

            Handler handler = null;
            try {
                handler = (Handler) field.get(this);

            if (handler != null && handler.getLooper() == Looper.getMainLooper()) {
                handler.removeCallbacksAndMessages(null);
            }
            field.setAccessible(false);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
